<template>
  <div class="transfers-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>调拨管理</h3>
          <div class="header-actions">
            <ExportButton 
              :data="tableData" 
              :columns="exportColumns" 
              filename="库存调拨"
              data-type="transfers"
              @export="handleExport"
            />
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新增调拨
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="调拨单号">
            <el-input v-model="searchForm.transferNo" placeholder="请输入调拨单号" clearable />
          </el-form-item>
          <el-form-item label="调出仓库">
            <el-select v-model="searchForm.fromWarehouse" placeholder="请选择调出仓库" clearable>
              <el-option 
                v-for="warehouse in warehouses" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="调入仓库">
            <el-select v-model="searchForm.toWarehouse" placeholder="请选择调入仓库" clearable>
              <el-option 
                v-for="warehouse in warehouses" 
                :key="warehouse.id" 
                :label="warehouse.name" 
                :value="warehouse.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="待审核" value="待审核" />
              <el-option label="已审核" value="已审核" />
              <el-option label="调拨中" value="调拨中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="transferNo" label="调拨单号" width="150" />
        <el-table-column prop="fromWarehouseName" label="调出仓库" width="120" />
        <el-table-column prop="toWarehouseName" label="调入仓库" width="120" />
        <el-table-column prop="totalQuantity" label="调拨数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作员" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="expectedDate" label="预计完成" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === '待审核'" 
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.status === '已审核'" 
              type="warning" 
              size="small" 
              @click="handleTransfer(row)"
            >
              调拨
            </el-button>
            <el-button 
              v-if="['待审核', '已审核'].includes(row.status)" 
              type="danger" 
              size="small" 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑调拨对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      @close="handleDialogClose"
    >
      <el-form
        ref="transferFormRef"
        :model="transferForm"
        :rules="transferRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调拨单号" prop="transferNo">
              <el-input v-model="transferForm.transferNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调出仓库" prop="fromWarehouse">
              <el-select v-model="transferForm.fromWarehouse" placeholder="请选择调出仓库" style="width: 100%" @change="handleFromWarehouseChange">
                <el-option 
                  v-for="warehouse in warehouses" 
                  :key="warehouse.id" 
                  :label="warehouse.name" 
                  :value="warehouse.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调入仓库" prop="toWarehouse">
              <el-select v-model="transferForm.toWarehouse" placeholder="请选择调入仓库" style="width: 100%" @change="handleToWarehouseChange">
                <el-option 
                  v-for="warehouse in warehouses" 
                  :key="warehouse.id" 
                  :label="warehouse.name" 
                  :value="warehouse.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员" prop="operator">
              <el-input v-model="transferForm.operator" placeholder="请输入操作员" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计完成" prop="expectedDate">
              <el-date-picker
                v-model="transferForm.expectedDate"
                type="date"
                placeholder="请选择预计完成日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="priority">
              <el-select v-model="transferForm.priority" placeholder="请选择紧急程度" style="width: 100%">
                <el-option label="普通" value="普通" />
                <el-option label="紧急" value="紧急" />
                <el-option label="特急" value="特急" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="transferForm.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息" 
          />
        </el-form-item>

        <!-- 商品明细 -->
        <el-form-item label="商品明细">
          <div class="product-list">
            <div class="product-header">
              <el-button type="primary" size="small" @click="addProduct">
                <el-icon><Plus /></el-icon>
                添加商品
              </el-button>
            </div>
            <el-table :data="transferForm.products" border>
              <el-table-column prop="productCode" label="商品编码" width="120">
                <template #default="{ row, $index }">
                  <el-input v-model="row.productCode" placeholder="商品编码" @blur="loadProductInfo(row, $index)" />
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" width="200">
                <template #default="{ row, $index }">
                  <el-input v-model="row.productName" placeholder="商品名称" readonly />
                </template>
              </el-table-column>
              <el-table-column prop="specification" label="规格" width="150">
                <template #default="{ row, $index }">
                  <el-input v-model="row.specification" placeholder="规格" readonly />
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="80">
                <template #default="{ row, $index }">
                  <el-input v-model="row.unit" placeholder="单位" readonly />
                </template>
              </el-table-column>
              <el-table-column prop="availableStock" label="可用库存" width="100">
                <template #default="{ row }">
                  {{ row.availableStock || 0 }}
                </template>
              </el-table-column>
              <el-table-column prop="transferQuantity" label="调拨数量" width="120">
                <template #default="{ row, $index }">
                  <el-input-number 
                    v-model="row.transferQuantity" 
                    :min="1" 
                    :max="row.availableStock"
                    style="width: 100%"
                    @change="calculateTotal"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="danger" size="small" @click="removeProduct($index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="total-info">
              <span>总调拨数量：<strong>{{ transferForm.totalQuantity }}</strong></span>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 调拨详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="调拨详情"
      width="800px"
    >
      <div v-if="currentTransfer">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="调拨单号">{{ currentTransfer.transferNo }}</el-descriptions-item>
          <el-descriptions-item label="调出仓库">{{ currentTransfer.fromWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="调入仓库">{{ currentTransfer.toWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="总调拨数量">{{ currentTransfer.totalQuantity }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentTransfer.status)">{{ currentTransfer.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="紧急程度">
            <el-tag :type="getPriorityType(currentTransfer.priority)">{{ currentTransfer.priority }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作员">{{ currentTransfer.operator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentTransfer.createTime }}</el-descriptions-item>
          <el-descriptions-item label="预计完成">{{ currentTransfer.expectedDate }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentTransfer.remark || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>商品明细</el-divider>
        <el-table :data="currentTransfer.products" border>
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="specification" label="规格" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="availableStock" label="可用库存" width="100" />
          <el-table-column prop="transferQuantity" label="调拨数量" width="120" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ExportButton from '@/components/common/ExportButton.vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const transferFormRef = ref()

// 搜索表单
const searchForm = reactive({
  transferNo: '',
  fromWarehouse: '',
  toWarehouse: '',
  status: '',
  dateRange: []
})

// 调拨表单
const transferForm = reactive({
  id: null,
  transferNo: '',
  fromWarehouse: '',
  fromWarehouseName: '',
  toWarehouse: '',
  toWarehouseName: '',
  operator: '',
  expectedDate: '',
  priority: '普通',
  remark: '',
  totalQuantity: 0,
  products: []
})

// 表单验证规则
const transferRules = {
  fromWarehouse: [
    { required: true, message: '请选择调出仓库', trigger: 'change' }
  ],
  toWarehouse: [
    { required: true, message: '请选择调入仓库', trigger: 'change' }
  ],
  operator: [
    { required: true, message: '请输入操作员', trigger: 'blur' }
  ],
  expectedDate: [
    { required: true, message: '请选择预计完成日期', trigger: 'change' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 仓库数据
const warehouses = ref([
  { id: 1, name: '主仓库', code: 'WH001' },
  { id: 2, name: '分仓库A', code: 'WH002' },
  { id: 3, name: '分仓库B', code: 'WH003' }
])

// 商品数据（模拟）
const products = ref([
  {
    id: 1,
    code: 'P001',
    name: 'iPhone 15',
    specification: '128GB 黑色',
    unit: '台',
    stock: { 1: 50, 2: 20, 3: 10 } // 各仓库库存
  },
  {
    id: 2,
    code: 'P002',
    name: 'MacBook Pro',
    specification: '13英寸 M2芯片',
    unit: '台',
    stock: { 1: 30, 2: 15, 3: 5 }
  }
])

// 表格数据
const tableData = ref([
  {
    id: 1,
    transferNo: 'TR20240115001',
    fromWarehouse: 1,
    fromWarehouseName: '主仓库',
    toWarehouse: 2,
    toWarehouseName: '分仓库A',
    totalQuantity: 10,
    status: '已完成',
    operator: '张三',
    createTime: '2024-01-15 10:00:00',
    expectedDate: '2024-01-16',
    priority: '普通',
    remark: '正常调拨',
    products: [
      {
        productCode: 'P001',
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        availableStock: 50,
        transferQuantity: 10
      }
    ]
  },
  {
    id: 2,
    transferNo: 'TR20240115002',
    fromWarehouse: 2,
    fromWarehouseName: '分仓库A',
    toWarehouse: 3,
    toWarehouseName: '分仓库B',
    totalQuantity: 5,
    status: '待审核',
    operator: '李四',
    createTime: '2024-01-15 14:00:00',
    expectedDate: '2024-01-17',
    priority: '紧急',
    remark: '',
    products: [
      {
        productCode: 'P002',
        productName: 'MacBook Pro',
        specification: '13英寸 M2芯片',
        unit: '台',
        availableStock: 15,
        transferQuantity: 5
      }
    ]
  }
])

const currentTransfer = ref(null)

// 导出列配置
const exportColumns = [
  { key: 'id', label: 'ID', type: 'number' },
  { key: 'transferNo', label: '调拨单号' },
  { key: 'fromWarehouseName', label: '调出仓库' },
  { key: 'toWarehouseName', label: '调入仓库' },
  { key: 'totalQuantity', label: '调拨数量', type: 'number' },
  { key: 'status', label: '状态' },
  { key: 'operator', label: '操作员' },
  { key: 'createTime', label: '创建时间', type: 'date' },
  { key: 'expectedDate', label: '预计完成' }
]

// 计算属性
const isEdit = computed(() => !!transferForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑调拨' : '新建调拨')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = tableData.value.length
    loading.value = false
  }, 500)
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    transferNo: '',
    fromWarehouse: '',
    toWarehouse: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
  generateTransferNo()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(transferForm, { ...row })
}

const handleView = (row) => {
  currentTransfer.value = row
  viewDialogVisible.value = true
}

const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核通过该调拨单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已审核'
      ElMessage.success('审核通过')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleTransfer = async (row) => {
  try {
    await ElMessageBox.confirm('确定要执行调拨吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已完成'
      ElMessage.success('调拨完成')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该调拨单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value[index].status = '已取消'
      ElMessage.success('调拨已取消')
      loadData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleFromWarehouseChange = (warehouseId) => {
  const warehouse = warehouses.value.find(w => w.id === warehouseId)
  if (warehouse) {
    transferForm.fromWarehouseName = warehouse.name
  }
}

const handleToWarehouseChange = (warehouseId) => {
  const warehouse = warehouses.value.find(w => w.id === warehouseId)
  if (warehouse) {
    transferForm.toWarehouseName = warehouse.name
  }
}

const loadProductInfo = (row, index) => {
  const product = products.value.find(p => p.code === row.productCode)
  if (product) {
    row.productName = product.name
    row.specification = product.specification
    row.unit = product.unit
    row.availableStock = product.stock[transferForm.fromWarehouse] || 0
  }
}

const addProduct = () => {
  transferForm.products.push({
    productCode: '',
    productName: '',
    specification: '',
    unit: '',
    availableStock: 0,
    transferQuantity: 0
  })
}

const removeProduct = (index) => {
  transferForm.products.splice(index, 1)
  calculateTotal()
}

const calculateTotal = () => {
  transferForm.totalQuantity = transferForm.products.reduce((total, product) => {
    return total + (product.transferQuantity || 0)
  }, 0)
}

const generateTransferNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  transferForm.transferNo = `TR${year}${month}${day}${random}`
}

const getStatusType = (status) => {
  const statusMap = {
    '待审核': 'warning',
    '已审核': 'primary',
    '调拨中': 'info',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const getPriorityType = (priority) => {
  const priorityMap = {
    '普通': 'info',
    '紧急': 'warning',
    '特急': 'danger'
  }
  return priorityMap[priority] || 'info'
}

const handleSubmit = async () => {
  if (!transferFormRef.value) return

  try {
    await transferFormRef.value.validate()
    
    if (transferForm.products.length === 0) {
      ElMessage.warning('请至少添加一个商品')
      return
    }

    if (transferForm.fromWarehouse === transferForm.toWarehouse) {
      ElMessage.warning('调出仓库和调入仓库不能相同')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEdit.value) {
      // 编辑调拨
      const index = tableData.value.findIndex(item => item.id === transferForm.id)
      if (index > -1) {
        tableData.value[index] = { ...transferForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增调拨
      const newTransfer = {
        ...transferForm,
        id: Date.now(),
        status: '待审核',
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newTransfer)
      ElMessage.success('新建成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(transferForm, {
    id: null,
    transferNo: '',
    fromWarehouse: '',
    fromWarehouseName: '',
    toWarehouse: '',
    toWarehouseName: '',
    operator: '',
    expectedDate: '',
    priority: '普通',
    remark: '',
    totalQuantity: 0,
    products: []
  })
  transferFormRef.value?.clearValidate()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleExport = (exportInfo) => {
  console.log('导出完成:', exportInfo)
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.transfers-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.product-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.product-header {
  margin-bottom: 10px;
}

.total-info {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  color: #e6a23c;
}
</style>
